#!/usr/bin/env python3
"""
graph_utils.py
Helpers to convert a list of events into a process-tree graph (networkx). Handles PID reuse by
using creation timestamp to build unique node ids.
"""
import networkx as nx
from datetime import datetime


def build_process_tree(events):
    # events: list of event dicts with pid, ppid, event, ts (iso)
    # we create nodes keyed by (pid, create_ts) to handle reuse. For simplicity, use first seen ts as creation.
    G = nx.DiGraph()
    creation = {}
    for e in events:
        pid = int(e.get('pid') or -1)
        etype = e.get('event')
        ts = e.get('ts')
        try:
            t = datetime.fromisoformat(ts)
        except Exception:
            t = datetime.utcnow()
        # treat exec or fork as creation
        if etype in (1,2):
            key = (pid, t.isoformat())
            creation[pid] = key
            G.add_node(key, comm=e.get('comm'), ts=t.isoformat())
            ppid = int(e.get('ppid') or -1)
            if ppid in creation:
                G.add_edge(creation[ppid], key)
    return G